package com.sxz.mall.mallsearch.service.impl;

import com.alibaba.fastjson.JSON;
import com.sxz.mall.common.dto.es.SkuESModel;
import com.sxz.mall.mallsearch.config.MallElasticSearchConfiguration;
import com.sxz.mall.mallsearch.constant.ESConstant;
import com.sxz.mall.mallsearch.service.MallSearchService;
import com.sxz.mall.mallsearch.vo.SearchParam;
import com.sxz.mall.mallsearch.vo.SearchResult;
import org.apache.lucene.search.join.ScoreMode;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.NestedQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.nested.NestedAggregationBuilder;
import org.elasticsearch.search.aggregations.bucket.nested.ParsedNested;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedLongTerms;
import org.elasticsearch.search.aggregations.bucket.terms.ParsedStringTerms;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.bucket.terms.TermsAggregationBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

//@Service
public class MallSearchServiceImpl_1 implements MallSearchService {

    @Autowired
    private RestHighLevelClient client;

    @Override
    public SearchResult search(SearchParam param) {

        SearchResult result = null;
        // 1、准备检索请求
        SearchRequest searchRequest = buildSearchRequest(param);
        // 2、执行检索操作
        try {
            SearchResponse response = client.search(searchRequest, MallElasticSearchConfiguration.COMMON_OPTIONS);
            //3、封装结果为SearchResult
            result = buildSearchResult(response, param);
        } catch (IOException e) {

        }


        return result;
    }

    private SearchResult buildSearchResult(SearchResponse response, SearchParam param) {
        SearchResult result = new SearchResult();

        // 处理response
        SearchHits hits = response.getHits();

        // 所有商品信息
        SearchHit[] products = hits.getHits();
        List<SkuESModel> list = new ArrayList<>();
        if (products != null && products.length > 0) {
            for (SearchHit product : products) {
                String sourceAsString = product.getSourceAsString();
                SkuESModel skuESModel = JSON.parseObject(sourceAsString, SkuESModel.class);
                if (!StringUtils.isEmpty(param.getKeyword())) {
                    HighlightField subTitle = product.getHighlightFields().get("subTitle");
                    String s = subTitle.fragments()[0].string();
                    skuESModel.setSubTitle(s); // 设置高亮，返回带b标签的字符串
                }

                list.add(skuESModel);
            }
            result.setProducts(list);
        }

        Aggregations aggregations = response.getAggregations();
        // 涉及到的所有品牌
        ParsedLongTerms brandAgg = aggregations.get("brand_agg");
        List<? extends Terms.Bucket> buckets = brandAgg.getBuckets();
        List<SearchResult.BrandVO> brandVOS = new ArrayList<>();
        if (buckets != null && buckets.size() > 0) {
            for (Terms.Bucket bucket : buckets) {
                SearchResult.BrandVO brandVO = new SearchResult.BrandVO();
                String keyAsString = bucket.getKeyAsString();
                brandVO.setBrandId(Long.parseLong(keyAsString)); // id

                // img
                ParsedStringTerms brandImgAgg = bucket.getAggregations().get("brand_img_agg");
                List<? extends Terms.Bucket> bucketsImg = brandImgAgg.getBuckets();
                if (bucketsImg != null && bucketsImg.size() > 0) {
                    String img = bucketsImg.get(0).getKeyAsString();
                    brandVO.setBrandImg(img);
                }

                // brandName
                ParsedStringTerms brandNameAgg = bucket.getAggregations().get("brand_name_agg");
                String brandName = brandNameAgg.getBuckets().get(0).getKeyAsString();
                brandVO.setBrandName(brandName);

                brandVOS.add(brandVO);
            }
        }

        result.setBrands(brandVOS);

        // 涉及到的类别信息
        ParsedLongTerms catalogAgg = aggregations.get("catalog_agg");
        List<? extends Terms.Bucket> bucketsCatalogs = brandAgg.getBuckets();
        List<SearchResult.CatalogVO> catalogVOS = new ArrayList<>();
        if (bucketsCatalogs != null && bucketsCatalogs.size() > 0) {
            for (Terms.Bucket bucket : bucketsCatalogs) {
                SearchResult.CatalogVO catalogVO = new SearchResult.CatalogVO();
                String keyAsString = bucket.getKeyAsString();
                catalogVO.setCatalogId(Long.parseLong(keyAsString));

                ParsedStringTerms catalogNameAgg = bucket.getAggregations().get("catalog_name_agg");
                String catalogName = catalogNameAgg.getBuckets().get(0).getKeyAsString();
                catalogVO.setCatalogName(catalogName);

                catalogVOS.add(catalogVO);
            }
        }
        result.setCatalogs(catalogVOS);

        // 属性信息
        ParsedNested attrAgg = aggregations.get("attr_agg");
        ParsedLongTerms attrIdAgg = attrAgg.getAggregations().get("attr_id_agg");
        List<? extends Terms.Bucket> bucketsAttr = attrIdAgg.getBuckets();
        List<SearchResult.AttrVo> attrVos = new ArrayList<>();

        if (bucketsAttr != null && bucketsAttr.size() > 0) {
            for (Terms.Bucket bucket : bucketsAttr) {
                SearchResult.AttrVo attrVo = new SearchResult.AttrVo();
                String keyAsString = bucket.getKeyAsString();
                attrVo.setAttrId(Long.parseLong(keyAsString));

                ParsedStringTerms attrNameAgg = bucket.getAggregations().get("attr_name_agg");
                String attrName = attrNameAgg.getBuckets().get(0).getKeyAsString();
                attrVo.setAttrName(attrName);

                ParsedStringTerms attrValueAgg = bucket.getAggregations().get("attr_value_agg");
                if (attrValueAgg != null && attrValueAgg.getBuckets().size() > 0) {
                    // 需要拼接为集合 todo
                    List<String> collect = attrValueAgg.getBuckets().stream().map((item) -> item.getKeyAsString())
                            .collect(Collectors.toList());

                    attrVo.setAttrValue(collect);
                }

                attrVos.add(attrVo);
            }
        }
        result.setAttrs(attrVos);

        // 分页信息
        long total = hits.getTotalHits().value; // 总条数
        result.setTotal(total);

        result.setPageNum(param.getPageNum());// 当前页

        // 总页数
        long l = total % ESConstant.PRODUCT_PAGESIZE;
        long pageNum = total / ESConstant.PRODUCT_PAGESIZE;
        long totalPage = l == 0 ? pageNum : pageNum + 1;
        result.setTotalPages((int) totalPage);

        return result;
    }

    private SearchRequest buildSearchRequest(SearchParam param) {
        SearchRequest searchRequest = new SearchRequest();
        searchRequest.indices(ESConstant.PRODUCT_INDEX);
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        // 构建具体的检索条件
        //1\构建bool查询
        BoolQueryBuilder boolQueryBuilder = QueryBuilders.boolQuery();
        if (!StringUtils.isEmpty(param.getKeyword())) {
            boolQueryBuilder.must(QueryBuilders.matchQuery("subTitle", param.getKeyword()));
        }
        if (param.getCatalog3Id() != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("catalogId", param.getCatalog3Id()));
        }
        if (param.getBrandId() != null && param.getBrandId().size() > 0) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("brandId", param.getBrandId()));
        }
        if (param.getHasStock() != null) {
            boolQueryBuilder.filter(QueryBuilders.termQuery("hasStock", param.getHasStock() == 1));
        }

        if (!StringUtils.isEmpty(param.getSkuPrice())) {
            RangeQueryBuilder skuPrice = QueryBuilders.rangeQuery("skuPrice");
            String[] s = param.getSkuPrice().split("_");
            if (s.length == 2) {
                skuPrice.gte(s[0]);
                skuPrice.lte(s[1]);
            } else if (s.length == 1) {
                if (param.getSkuPrice().endsWith("_")) {
                    skuPrice.gte(s[0]);
                }
                if (param.getSkuPrice().startsWith("_")) {
                    skuPrice.lte(s[1]);
                }
            }
            boolQueryBuilder.filter(skuPrice);
        }


        // nested单独加query   19_32GB:64GB
        if (param.getAttrs() != null && param.getAttrs().size() > 0) {

            for (String attrStr : param.getAttrs()) {
                BoolQueryBuilder boolNestedBuilder = QueryBuilders.boolQuery();
                String[] s = attrStr.split("_");
                String attrId = s[0]; // 编号
                String[] values = s[1].split(":");

                boolNestedBuilder.must(QueryBuilders.termQuery("attrs.attrId", attrId));
                boolNestedBuilder.must(QueryBuilders.termQuery("attrs.attrValue", values));

                NestedQueryBuilder nestedQuery = QueryBuilders.nestedQuery("attrs", boolNestedBuilder, ScoreMode.None);

                boolQueryBuilder.filter(nestedQuery);
            }

        }

        searchSourceBuilder.query(boolQueryBuilder);

        // 排序  salaCount_asc/desc
        if (!StringUtils.isEmpty(param.getSort())) {
            String[] s = param.getSort().split("_");
            SortOrder sortOrder = s[1].equalsIgnoreCase("asc") ? SortOrder.ASC : SortOrder.DESC;
            searchSourceBuilder.sort(s[0], sortOrder);
        }
        // 分页
        if (param.getPageNum() != null) {
            searchSourceBuilder.from((param.getPageNum() - 1) * ESConstant.PRODUCT_PAGESIZE);
            searchSourceBuilder.size(ESConstant.PRODUCT_PAGESIZE);
        }
        // 高亮
        if (!StringUtils.isEmpty(param.getKeyword())) {
            HighlightBuilder highlightBuilder = new HighlightBuilder();
            highlightBuilder.field("subTitle");
            highlightBuilder.preTags("<b style='color:red'>");
            highlightBuilder.preTags("<b/>");
            searchSourceBuilder.highlighter(highlightBuilder);
        }

        //聚合运算
        // 品牌聚合
        TermsAggregationBuilder brandAgg = AggregationBuilders.terms("brand_agg");
        brandAgg.field("brandId");
        brandAgg.size(50);
        // 品牌子聚合
//        brandAgg.subAggregation(AggregationBuilders.terms("brand_name_agg").field("brandName").size(10));
        brandAgg.subAggregation(AggregationBuilders.terms("brand_img_agg").field("brandImg").size(10));
        searchSourceBuilder.aggregation(brandAgg);

        // 类别聚合
        TermsAggregationBuilder catalogAgg = AggregationBuilders.terms("catalog_agg");
        catalogAgg.field("catalogId");
        catalogAgg.size(10);
        // 类别子聚合
        catalogAgg.subAggregation(AggregationBuilders.terms("catalog_name_agg").field("catalogName").size(10));
        searchSourceBuilder.aggregation(catalogAgg);

        // 属性的聚合
        NestedAggregationBuilder attrAgg = AggregationBuilders.nested("attr_agg", "attrs");
        TermsAggregationBuilder attrIdAgg = AggregationBuilders.terms("attr_id_agg");
        attrAgg.subAggregation(attrIdAgg.field("attrs.attrId").size(10));
        // id子聚合
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_name_agg").field("attrs.attrName").size(10));
        attrIdAgg.subAggregation(AggregationBuilders.terms("attr_value_agg").field("attrs.attrValue").size(10));

        searchSourceBuilder.aggregation(attrAgg);


//        System.out.println(searchSourceBuilder.toString());


        searchRequest.source(searchSourceBuilder);
        return searchRequest;
    }
}